package logger

import (
	"context"
	"fmt"
	"reflect"
	"time"

	"github.com/olivere/elastic/v7"
)

func NewElasticsearch(ctx context.Context, endpoint, index string) *Elasticsearch {
	client, err := elastic.NewClient(elastic.SetURL(endpoint), elastic.SetSniff(false))
	if err != nil {
		fmt.Printf("Error creating the Elasticsearch client: %v", err)
	}

	return &Elasticsearch{
		ctx:    ctx,
		client: client,
		index:  index,
	}
}

type Elasticsearch struct {
	ctx    context.Context
	client *elastic.Client
	index  string
}

type Log struct {
	Message   string
	Timestamp string
}

func (r *Elasticsearch) Log(message string) error {
	doc := Log{
		Message:   message,
		Timestamp: time.Now().Format(time.RFC3339),
	}

	_, err := r.client.Index().
		Index(r.index).
		// Type("tweet").
		// Id("1").
		BodyJson(doc).
		Do(r.ctx)
	if err != nil {
		return fmt.Errorf("failed to logger to Elasticsearch: %v", err)
	}

	return nil
}
func (r *Elasticsearch) List() error {
	// term := elastic.NewTermQuery("user", "olivere")
	result, err := r.client.Search().
		Index(r.index).
		// Query(term).
		// Sort("user", true).
		From(0).Size(10).
		Pretty(true).
		Do(r.ctx)
	if err != nil {
		return err
	}

	var log Log
	fmt.Println(result.TookInMillis, result.TotalHits())
	for _, item := range result.Each(reflect.TypeOf(log)) {
		if t, ok := item.(Log); ok {
			fmt.Printf("%s: %s\n", t.Timestamp, t.Message)
		}
	}

	return nil
}

// index

func (r *Elasticsearch) CreateIndex() error {
	_, err := r.client.
		CreateIndex(r.index).
		Do(r.ctx)
	return err
}
func (r *Elasticsearch) DeleteIndex() error {
	_, err := r.client.
		DeleteIndex(r.index).
		Do(r.ctx)
	return err
}
